const Koa = require("koa")
const router = require("koa-router")()
const parser = require("koa-parser")
const cors = require("koa-cors")

const app = new Koa();

app.use(parser())
app.use(cors())

// let fruitList = [
//   { name: "apple" },
//   { name: "banana" },
//   { name: "pear" }
// ];
let fruitList = ["apple", "banana", "pear"]
router.get("/api/fruitList", async ctx => {
  ctx.body = fruitList;
})

router.post("/api/fruitList", async ctx => {
  let { fruit } = ctx.request.body;
  fruitList.push(fruit);
  ctx.body = { errno: 0, msg: "添加成功！" };
})

router.put("/api/fruitList/:index", async ctx => {
  let { index } = ctx.params;
  let { updateFruit } = ctx.request.body;
  fruitList.splice(index, 1, updateFruit)
  ctx.body = { errno: 0, msg: "修改成功！" };
})

router.del("/api/fruitList/:index", async ctx => {
  let { index } = ctx.params;
  console.log(index)
  fruitList.splice(index, 1)
  ctx.body = { errno: 0, msg: "删除成功！" };
})

app.use(router.routes())

app.listen(5000, () => {
  console.log("running on 5000, http://localhost:5000")
})